<template>
	<view class="ljapp">
		<view v-if="group.loaded&&group.list.length<=0">
			<u-navbar placeholder autoBack leftIconColor="#fff" titleStyle ="color:#fff;" title="接诊大厅" bgColor="rgb(53,107,253)"></u-navbar>
			<lj-empty>暂无患者</lj-empty>
		</view>
		<view v-else-if="group.list.length>0">
			<view class="doctor">
				<view class="header" :style="'background-image: url('+$base.cdn('/uploads/20220408/ea676fac98b92b4d7b3172b6256a86af.png')+');'">
					<u-navbar placeholder autoBack leftIconColor="#fff" titleStyle ="color:#fff;" title="接诊大厅" :bgColor="'rgba(53,107,253,'+navbarBgAlpha+')'"></u-navbar>
					<view class="outer">
						<view class="userinfo u-flex u-flex-y-center">
							<image class="avatar" :src="$base.cdn(group.list[current].order_info.user_headimgurl)" mode="aspectFill"></image>
							<view class="u-flex u-flex-fill ">
								<view class="info u-flex-fill">
									<view class="nickname">
										{{group.list[current].order_info.user_the_patient_info.name}}
										<text style="margin-left: 36rpx;">{{group.list[current].order_info.user_the_patient_info.sex==1?'男':'女'}}</text>
										<text style="margin-left: 30rpx;">{{group.list[current].order_info.user_the_patient_info.age}}岁</text>
									</view>
									<view class="u-flex">
										<view class="date">
											<!-- 10分钟前 -->
											{{$base.timestampFormat(group.list[current].createtime)}}
										</view>
									</view>
								</view>
								<view class="btn-capsule" style="width: auto;padding: 0 20rpx;">
									<block v-if="group.list[current].type=='tw'">图文问诊</block>
									<block v-else-if="group.list[current].type=='sp'">视频问诊</block>
									<block v-else-if="group.list[current].type=='report'">报告解读</block>
									￥{{group.list[current].order_info.money}}
								</view>
							</view>
						</view>

						<view class="menu" style="height:156rpx;"></view>
					</view>
				</view>
			</view>

			<view class="content">
				<view class="card">
					<view class="tit u-flex">
						<image src="/static/lj/common/icon_describe.png" mode="aspectFill"></image>
						<view>病症描述</view>
					</view>
					<view class="con">
						<view class="file" v-if="group.list[current].type=='report'">
							<view class="inn u-flex u-flex-y-center" @click="openFile(group.list[current].order_info)">
								<view>
									<view class="tit">{{group.list[current].order_info.report_filename}}</view>
									<view class="ftime">{{group.list[current].order_info.report_time}}</view>
								</view>
								<image :src="'/static/lj/common/filepdf.png'" mode=aspectFill></image>
							</view>
						</view>
						<view v-else>{{group.list[current].order_info.content}}</view>
					</view>
					<view class="scon" v-if="group.list[current].type!='report'">咨询目的：{{group.list[current].order_info.consultation_consult_name}}</view>
					<view class="time">下单时间：{{$u.timeFormat(group.list[current].order_info.createtime,'yyyy-mm-dd hh:MM:ss')}}</view>
					<view class="imglist u-flex u-flex-wrap" v-if="group.list[current].order_info.images && group.list[current].order_info.images.length>0">
						<image :src="img" mode="aspectFill" v-for="(img,index) in group.list[current].order_info.images" :key="index"></image>
					</view>
				</view>
			</view>

			<view class="foot-fixed">
				<view class="inner u-flex u-flex-between">
					<view class="prev-btn gray" v-if="current==0">上一条</view>
					<view class="prev-btn" @click="changeCurrent(-1)" v-else>上一条</view>
					<view class="next-btn gray" v-if="current>=(group.list.length-1)">下一条</view>
					<view class="next-btn" @click="changeCurrent(1)" v-else>下一条</view>
				</view>

				<view class="receive-btn" @click="receivePatient">接诊</view>
			</view>
		</view>

		<u-popup :show="show" :round="8" mode="center">
			<view class="popup-submit-content u-flex u-flex-y-center">
				<image src="/static/lj/common/thumbs.png" mode="aspectFill"></image>
				<view class="u-flex-fill">
					<view class="tit">接诊成功！</view>
					<view class="con">（{{popupSubmitTime}}s后自动关闭）</view>
				</view>
			</view>
		</u-popup>
	</view>

</template>

<script>
	export default {
		data() {
			return {
				navbarBgAlpha: 0,
				userInfo: {}, //用户信息
				doctorobj: {},
				
				show: false,
				popupSubmitTimer: null,
				popupSubmitTime: 5,
				current: 0,

				group:{
					page: 1,
					limit: 10,
					list: [],
					loaded: false
				},
				loading: false,
			}
		},
		onLoad(){
			if(!this.$store.state.IsOpen){
				uni.showLoading({
					title: '正在连接服务器...',
					mask: true
				});
			}
			uni.$on("onImStatus",(rel)=>{
			    console.log('==>>我被全局通知了onImStatus', rel)
				
				if(!rel.IsOpen){
					uni.showLoading({
						title: '正在连接服务器...',
						mask: true
					});
				}else{
					uni.hideLoading()
				}
			})
			
			this.$Http({
				url: 'getUserInfo',
				type: 'POST',
				data: {}
			}).then(res => {
				if (res.code == 1) {
					this.userInfo = res.data
					this.doctorobj = this.userInfo.doctor_info
				}
			})
		},
		onUnload(){
			uni.$off("onImStatus")
		},
		onShow() {
			this.init()
		},
		onPageScroll: function(e) {
			var a = e.scrollTop/80
			this.navbarBgAlpha = a>1?1:a
		},
		methods: {
			init(){
				this.group.page = 1
				this.group.list = []
				this.group.loaded = false
				this.loading = false

				this.getList();
			},
			getList(){
				var that = this,group = that.group;
				if(that.loading || group.loaded) return;

				that.loading = true

				this.$Http({
					url: 'doctorGrabPatientList',
					data: {
						page: group.page,
						limit: group.limit,
					},
					type:'POST',
				}).then(res=>{
					if(res.code == 1){
						var list = res.data.data;
						group.loaded = list.length < group.limit;
						group.page ++;
						group.list = group.list.concat(list);
					}

					that.loading = false
				}).catch(()=>{
					that.loading = false
				});
			},
			changeCurrent(e){
				if(e<0 && this.current<=0) return false
				if(e>0 && this.current>=(this.group.list.length-1)) return false

				this.current += e
				if(e>0 && this.current>=(this.group.list.length-4)){
					this.getList()
				}
			},
			// 接诊
			receivePatient(){
				var that = this, grabPatientInfo = that.group.list[that.current], id = grabPatientInfo.id

				if(!this.$store.state.IsOpen){
					uni.showLoading({
						title: '正在连接服务器...',
						mask: true
					});
					return false
				}
				
				if(id){//图文问诊
					uni.showModal({
						title: '操作提示',
						confirmText: '确定',
						confirmColor: '#6bcbb6',
						cancelText: '取消',
						content: '您确定要接诊吗',
						success: function(res) {
							if (res.confirm) {
								that.$Http({
									url: 'consultationQuickPatient',
									type: 'POST',
									show: true,
									data: {id: id}
								}).then(res => {
									if(res.code==1){
										that.popupSubmitTime = 5
										that.show = true
										
										var cate = 'text', orderno = grabPatientInfo.order_info.order_code
										if(grabPatientInfo.type=='sp') cate = 'video'
										else if(grabPatientInfo.type=='report') cate = 'report'
										
										var FromUser = {
											prefix: "HZ",
											uid: grabPatientInfo.order_info.user_id,
											nick: grabPatientInfo.order_info.user_the_patient_info.name,
											avatar: that.$base.cdn(grabPatientInfo.order_info.user_headimgurl)
										}
										var ToUser = {
											prefix: "DT",
											uid: that.userInfo.id,
											nick: that.doctorobj.name,
											avatar: that.$base.cdn(that.doctorobj.img)
										}
										that.$store.commit('createToUser', {FromUser:ToUser, ToUser:FromUser, orderno:orderno})
										
										var chatList = []
										if(cate == 'report'){
											chatList.push({
												cate: cate,
												orderno: orderno,
												fromType: 'user',
												from: FromUser,
												to: ToUser,
												type: 'text',
												content: {
													text: "您好，这是我的检测报告<br>麻烦帮忙看一下，谢谢！"
												},
												time: grabPatientInfo.order_info.pay_time
											})
											chatList.push({
												cate: cate,
												orderno: orderno,
												fromType: 'user',
												from: FromUser,
												to: ToUser,
												type: 'file',
												content: {
													type: 'pdf',
													name: grabPatientInfo.order_info.report_filename,
													url: grabPatientInfo.order_info.report_url,
													time: grabPatientInfo.order_info.report_time
												},
												time: grabPatientInfo.order_info.pay_time
											})
										}else{
											chatList.push({
												cate: cate,
												orderno: orderno,
												fromType: 'user',
												from: FromUser,
												to: ToUser,
												type: 'textCard',
												content: {
													list: [
														{name:"咨询类型", value:grabPatientInfo.order_info.consultation_consult_name},
														{name:"病情描述", value:grabPatientInfo.order_info.content},
														// {name:"就诊情况", value:this.orderInfo.content},
													]
												},
												time: grabPatientInfo.order_info.pay_time//createtime
											})
											
											if(grabPatientInfo.order_info.images){
												var images = grabPatientInfo.order_info.images.toString().split(","), imgs = [], num = images.length
												for(var i in images){
													if(images[i]){
														imgs.push({
															url: images[i],
															w: 430/(num-1)
														})
													}
												}
												if(imgs.length>0){
													chatList.push({
														cate: cate,
														orderno: orderno,
														fromType: 'user',
														from: FromUser,
														to: ToUser,
														type: 'imgs',
														content: {
															list: imgs
														},
														time: grabPatientInfo.order_info.pay_time//createtime
													})
												}
											}
										}
										
										that.popupSubmitTime = 5
										that.show = true
										// 向患者发送接诊通知
										that.$store.dispatch('sendChatMessage',{
											cate: cate,
											orderno: orderno,
											type: 'consultationHandle',
											content:{
												code: "receivePatient",
												orderStatus: 1,
												patient_timing: res.data,
												chatList: chatList,
											},
										})
										that.$store.commit('closeToUser')
										
										that.current = 0
										that.init()

										that.popupSubmitTimer = setInterval(function(){
											that.popupSubmitTime--
											if(that.popupSubmitTime<=0){
												that.show = false
												if(that.popupSubmitTimer!=null){
													clearInterval(that.popupSubmitTimer)
													that.popupSubmitTimer = null
												}
												uni.navigateTo({
													url: '/pagesA/message/chat?isDoc=1&cate='+cate+'&orderno='+orderno
												})
											}
											// that.group.list.splice(that.current,1)
										},1000)
									}
								})
							}
						},
					})
				}else{
					uni.showToast({
						icon: 'none',
						duration: 3000,
						title: '参数错误'
					});
				}
			},
			
			// 判断文件类型
			whatFileType(url){
				let sr = url.lastIndexOf('.') //  最后一次出现的位置
				let fileType = url.substr((sr+1)) // 截取url的类型
				return(fileType)
			},
			openFile(item){
				console.log('openFile',item)
				var that = this
				item.report_filetype = 'pdf'
				if(item.report_filetype=='pdf'){
					uni.showLoading({
						title: '加载中',
						mask: true
					})
					
					let fileType = this.whatFileType(item.report_url)
					console.log(wx.env.USER_DATA_PATH + "/"+ (new Date().getTime()) + "."+fileType)
					uni.downloadFile({
						url: that.$base.img(item.report_url),
						// filePath: wx.env.USER_DATA_PATH + "/"+ (new Date().getTime()) + "."+fileType,
						success(res){
							uni.hideLoading()
							var filePath = res.tempFilePath
							uni.showLoading({
								title: '正在打开',
								mask: true
							})
							
							uni.openDocument({
								filePath: filePath,
								// fileType: item.type,
								// showMenu: true,
								// flieType: fileType,
								success(res) {
									uni.hideLoading()
									
								},
								fail(err){
									console.log('openDocument', err)
									uni.hideLoading()
									that.$u.toast('打开失败');
								}
							})
						},
						fail(err){
							console.log('downloadFile', err)
							uni.hideLoading()
							that.$u.toast('加载失败');
						}
					})
				}else{
					that.$u.toast('开始下载【'+item.report_filename+'】');
					uni.downloadFile({
						url: that.$base.img(item.report_url),
						success: (res) => {
							if (res.statusCode === 200) {
								console.log('下载成功');
								that.$u.toast('下载成功');
							}
						}
					})
				}
			},
		}
	}
</script>

<style lang="less">
	@import '@/pages/style.less';

	.doctor{
		padding-bottom: 0;

		.header{
			background-color: transparent;
		}
	}
	.content{
		position: relative;
		padding: 0 24rpx 168rpx;
		margin-top: -156rpx;
		.card{
			padding: 20rpx 36rpx 54rpx;
			background-color: #fff;
			border-radius: 10rpx;

			.tit{
				image{
					width: 42rpx;
					min-width: 42rpx;
					height: 42rpx;
					margin-right: 12rpx;
				}
			}
			.con{
				font-size: 24rpx;
				color: #666666;
				background-color: #fff;
				border-radius: 10rpx;
				margin-top: 20rpx;
				
				.file{
					display: inline-block;
					.inn{
						background: #f6f6f6;
						border-radius: 8rpx;
						padding: 20rpx;
					}
					.tit{
						font-size: 22rpx;
						// color: #666;
					}
					image{
						display: block;
						width: 60rpx;
						height: 76rpx;
						margin-left: 40rpx;
					}
				}
			}
			.scon{
				margin-top: 20rpx;
			}
			.time{
				margin-top: 10rpx;
			}
			.imglist{
				margin-top: 40rpx;

				image{
					width: 144rpx;
					height: 126rpx;
					border-radius: 8rpx;
					margin-right: 16rpx;
					margin-bottom: 26rpx;

					&:nth-child(4n){
						margin-right: 0;
					}
				}
			}
		}

	}
	.foot-fixed{
		position: fixed;
		bottom: 0;
		width: 100%;
		z-index: 9999;

		.inner{
			height: 100rpx;
			line-height: 100rpx;
			color: #333333;
			font-size: 28rpx;
			padding: 0 60rpx;
			background-color: #fff;
		}
		.prev-btn,.next-btn{
			width: 124rpx;
			height: 100%;
			text-align: center;

			&.gray{
				color: #999999;
			}
		}
		.receive-btn{
			position: absolute;
			left: 50%;
			bottom: 28rpx;
			margin-left: -64rpx;
			width: 128rpx;
			height: 128rpx;
			line-height: 128rpx;
			text-align: center;
			color: #fff;
			font-size: 28rpx;
			border-radius: 50%;
			background-color: #356bfd;
		}
	}

	.popup-submit-content{
		image{
			display: block;
			width: 56rpx;
			min-width: 56rpx;
			height: 56rpx;
		}
	}
</style>
